import { ref, computed } from 'vue';
import * as echarts from 'echarts';

/**
 * 获取图表主题配色方案
 * @description 返回预设的主题颜色数组，用于图表系列的配色
 * @returns {string[]} 颜色数组 - 包含多个十六进制颜色值
 */
export const useColors = () => [
    '#00f4ff',  // 青色
    '#0a8bc8',  // 蓝色
    '#f9b523',  // 黄色
    '#ff6b6b',  // 红色
    '#4ecdc4',  // 青绿色
    '#45b7d1',  // 湖蓝色
];

/**
 * 获取图表通用配置
 * @description 返回 ECharts 图表的基础样式配置，包括背景、文字、边框等
 * @returns {Object} 通用配置对象
 */
export const useCommonConfig = () => ({
    backgroundColor: 'transparent',
    textStyle: {
        color: '#ffffff',
        fontFamily: '"Microsoft YaHei", sans-serif'
    },
    title: {
        textStyle: {
            color: '#ffffff',
            fontSize: 16,
            fontWeight: 'bold'
        },
        left: 'center'
    },
    tooltip: {
        backgroundColor: 'rgba(3, 65, 105, 0.9)',
        borderColor: '#026688',
        borderWidth: 1,
        padding: [10, 15],
        textStyle: {
            color: '#ffffff',
            fontSize: 14
        }
    },
    axisLabel: {
        color: '#ffffff',
        fontSize: 12
    },
    axisLine: {
        lineStyle: {
            color: '#ffffff',
            width: 1
        }
    }
});

/**
 * 生成随机测试数据
 * @description 生成指定范围和数量的随机数据数组，用于开发测试
 * @param {number} min - 数据最小值
 * @param {number} max - 数据最大值
 * @param {number} count - 需要生成的数据点数量
 * @returns {Ref<number[]>} Vue 响应式数据，包含随机数值数组
 */
export const useRandomData = (min, max, count) => {
    return ref(Array.from({ length: count }, () => +(Math.random() * (max - min) + min).toFixed(2)));
};

/**
 * 生成饼图/环形图配置
 * @description 创建饼图或环形图的完整配置，支持自定义标题、数据和样式
 * @param {Object} config - 图表配置对象
 * @param {string} config.title - 图表标题
 * @param {Array} config.data - 图表数据数组
 * @param {boolean} config.isDonut - 是否为环形图
 * @returns {ComputedRef<Object>} 图表配置计算属性
 */
export const usePieChartOption = (config) => {
    const { title, data, isDonut } = config;
    const commonConfig = useCommonConfig();

    return computed(() => ({
        ...commonConfig,
        title: {
            text: title,
            textStyle: { color: '#ffffff' }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 10,
            top: 'center',
            textStyle: {
                color: '#ffffff',
                fontSize: 12
            },
            itemWidth: 10,
            itemHeight: 10
        },
        series: [{
            name: title,
            type: 'pie',
            radius: isDonut ? ['45%', '70%'] : '60%',
            center: ['60%', '50%'],
            data: data,
            label: {
                color: '#ffffff',
                fontSize: 12,
                formatter: '{b}\n{d}%'
            },
            labelLine: {
                length: 10,
                length2: 15,
                smooth: true
            },
            itemStyle: {
                borderRadius: 5,
                borderWidth: 2,
            },
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }]
    }));
};
/**
 * 生成排名图配置
 * @description 创建横向或纵向的排名图表配置，支持渐变色和自动排序
 * @param {string} title - 图表标题
 * @param {Array<Object>} data - 数据数组，每个对象包含 name 和 value 属性
 * @param {boolean} [isHorizontal=true] - 是否为横向排名图
 * @param {Array<string>} [gradientColors=['#83bff6', '#188df0']] - 渐变色数组
 * @returns {ComputedRef<Object>} 图表配置计算属性
 */
export const useRankingChartOption = (title, data, isHorizontal = true, gradientColors = ['#83bff6', '#188df0']) => {
    const commonConfig = useCommonConfig();
    return computed(() => {
        const sortedData = [...data].sort((a, b) => b.value - a.value);
        const names = sortedData.map(item => item.name);
        const values = sortedData.map(item => item.value);

        const defaultShowCount = Math.min(10, Math.ceil(data.length / 3));
        const defaultEnd = Math.min(100, Math.max(30, (defaultShowCount / data.length) * 100));

        // 基础配置
        const baseConfig = {
            ...commonConfig,
            title: {
                text: title,
                textStyle: { color: '#ffffff' },
                left: '3%',
                top: 10
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow', shadowStyle: { color: 'rgba(0,0,0,0.1)' } },
                triggerOn: 'mousemove|click',
                confine: true,
                enterable: true,
                textStyle: { fontSize: 14 },
                padding: [8, 12]
            },
            grid: {
                top: '15%',
                left: '3%',
                right: isHorizontal ? '10%' : '5%',
                bottom: data.length > 100 ? '20%' : '5%',
                containLabel: true
            },
            xAxis: isHorizontal ? {
                type: 'value',
                axisLabel: { color: '#ffffff', fontSize: 12 },
                splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
            } : {
                type: 'category',
                data: names,
                axisLabel: { rotate: 45, fontSize: 12, color: '#ffffff', interval: 0, hideOverlap: true }
            },
            yAxis: isHorizontal ? {
                type: 'category',
                data: names,
                axisLabel: { fontSize: 12, color: '#ffffff', interval: 0, hideOverlap: true },
                inverse: true
            } : {
                type: 'value',
                axisLabel: { color: '#ffffff', fontSize: 12 },
                splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
            },
            series: [{
                name: '数值',
                type: 'bar',
                data: values,
                barWidth: isHorizontal ? 20 : '40%',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, isHorizontal ? 1 : 0, isHorizontal ? 0 : 1,
                        [{ offset: 0, color: gradientColors[0] }, { offset: 1, color: gradientColors[1] }]
                    ),
                    borderRadius: 4
                },
                label: { show: false },
                emphasis: {
                    focus: 'series',
                    scale: true,
                    scaleSize: 10
                }
            }],
            animation: true,
            animationDuration: 300,
            animationEasing: 'cubicOut',
            progressive: 500,
            progressiveThreshold: 3000,
            useDirtyRect: true,
            touchMoveThreshold: 5
        };

        if (data.length > 100) {
            baseConfig.dataZoom = [
                {
                    type: 'slider',
                    yAxisIndex: isHorizontal ? 0 : undefined,
                    xAxisIndex: isHorizontal ? undefined : 0,
                    width: isHorizontal ? 12 : undefined,
                    height: isHorizontal ? undefined : 30,
                    right: isHorizontal ? 0 : undefined,
                    bottom: isHorizontal ? undefined : 0,
                    start: 0,
                    end: defaultEnd,
                    showDetail: true,
                    filterMode: 'empty',
                    textStyle: { color: '#ffffff', fontSize: 12 },
                    handleSize: '100%',
                    handleStyle: {
                        color: '#ffffff',
                        borderColor: '#ffffff',
                        borderWidth: 1,
                        borderRadius: 10,
                        shadowBlur: 3,
                        shadowColor: 'rgba(0,0,0,0.4)'
                    },
                    moveHandleStyle: { color: '#ffffff' },
                    backgroundColor: 'rgba(255,255,255,0.1)',
                    fillerColor: 'rgba(255,255,255,0.2)',
                    borderColor: 'transparent',
                    emphasis: { handleStyle: { borderWidth: 2, shadowBlur: 6 } },
                    zoomLock: false,
                    brushSelect: false,
                    preventDefaultMouseMove: true
                },
                {
                    type: 'inside',
                    yAxisIndex: isHorizontal ? 0 : undefined,
                    xAxisIndex: isHorizontal ? undefined : 0,
                    start: 0,
                    end: defaultEnd,
                    zoomOnMouseWheel: true,
                    moveOnMouseMove: true,
                    moveOnMouseWheel: true,
                    zoomLock: false,
                    disabled: false,
                    zoomOnMouseWheel: 'shift',
                    rangeMode: ['value', 'value']
                }
            ];

            // 当有 dataZoom 时，调整 grid 的右侧边距
            if (isHorizontal) {
                baseConfig.grid.right = '10%';
            } else {
                baseConfig.grid.bottom = '20%'; // 为横向 dataZoom 留出空间
            }
        }

        return baseConfig;
    });
};
/**
 * 图表配置生成函数
 * @param {Object} config - 图表配置参数
 * @param {string} config.title - 图表标题
 * @param {Array<string|number>} config.xAxisData - X轴数据
 * @param {Array<SeriesConfig>} config.series - 数据系列配置数组
 * @param {boolean} [config.iszoom=false] - 是否启用缩放功能
 * @param {boolean} [config.showMarkLine=false] - 是否显示标记线
 * @param {number} [config.defaultShowCount=30] - 默认显示的数据点数量
 * @param {Array<string>} [config.customColors] - 自定义颜色数组
 * @param {Object} [config.gridPadding] - 图表网格内边距配置
 * @param {boolean} [config.isStacked=false] - 是否为堆叠图
 * @returns {ComputedRef<Object>} ECharts 配置对象
 * 
 * @example
 * // 使用自定义颜色的示例
 * const option = useComparisonChartOption({
 *   title: '销售趋势',
 *   xAxisData: ['1月', '2月', '3月'],
 *   series: [{
 *     name: '销售额',
 *     data: [100, 200, 150],
 *     type: 'line',
 *     showExtremum: true
 *   }],
 *   customColors: ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4'],
 *   iszoom: true,
 *   showMarkLine: true
 * });
 */
export const useComparisonChartOption = ({
    title,
    xAxisData,
    series,
    iszoom = false,
    showMarkLine = false,
    customColors,
    gridPadding = {},
    isStacked = false // 新增堆叠配置参数
}) => {
    // 默认网格配置
    const defaultGridPadding = {
        top: '15%',
        right: '8%',
        bottom: iszoom ? '20%' : '3%',
        left: '3%',
        ...gridPadding
    };

    return computed(() => {
        const defaultEnd = Math.min(100, Math.max(30, 100 / Math.ceil(xAxisData.length / 4)));
        const colors = customColors || useColors();

        const baseConfig = {
            backgroundColor: 'transparent',
            title: {
                text: title,
                textStyle: { color: '#fff', fontSize: 18, fontWeight: 'bold' },
                top: 10,
                left: '3%'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'cross', crossStyle: { color: '#fff', width: 1, type: 'dashed' } },
                backgroundColor: 'rgba(0,0,0,0.8)',
                borderColor: '#fff',
                borderWidth: 1,
                padding: [10, 15],
                textStyle: { color: '#fff', fontSize: 13 },
                triggerOn: 'mousemove|click',
                enterable: true,
                confine: true
            },
            legend: {
                data: series.map(s => s.name),
                textStyle: { color: '#fff', fontSize: 12 },
                right: '5%',
                top: 10,
                icon: 'roundRect',
                itemWidth: 10,
                itemHeight: 10,
                itemGap: 20,
                selectedMode: 'multiple'
            },
            grid: { ...defaultGridPadding, containLabel: true },
            xAxis: {
                type: 'category',
                data: xAxisData,
                axisLabel: { color: '#fff', interval: 'auto', rotate: 30, fontSize: 12 },
                axisLine: { lineStyle: { color: 'rgba(255,255,255,0.3)' } },
                axisTick: { show: false }
            },
            yAxis: {
                type: 'value',
                axisLabel: { color: '#fff', fontSize: 12 },
                splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)', type: 'dashed' } }
            },
            series: series.map((s, index) => {
                const baseSeriesConfig = {
                    ...s,
                    itemStyle: {
                        color: colors[index % colors.length],
                        borderRadius: s.type === 'bar' ? [4, 4, 0, 0] : 0
                    },
                    emphasis: {
                        focus: 'series',
                        scale: true,
                        scaleSize: 10,
                        itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.5)' }
                    }
                };

                // 线图特殊配置
                if (s.type === 'line') {
                    Object.assign(baseSeriesConfig, {
                        lineStyle: {
                            width: 3,
                            shadowColor: 'rgba(0,0,0,0.3)',
                            shadowBlur: 10
                        },
                        smooth: 0.2,
                        showSymbol: true,
                        symbol: 'circle',
                        symbolSize: 8
                    });
                }

                // 柱图特殊配置
                if (s.type === 'bar') {
                    baseSeriesConfig.barMaxWidth = 30;
                    // 添加堆叠配置
                    if (isStacked) {
                        baseSeriesConfig.stack = 'total';
                        // 堆叠图的提示信息格式化
                        baseConfig.tooltip.formatter = (params) => {
                            let result = `${params[0].axisValueLabel}<br/>`;
                            let total = 0;
                            params.forEach(param => {
                                if (param.seriesType === 'bar') {
                                    total += param.value;
                                    result += `${param.marker} ${param.seriesName}: ${param.value}<br/>`;
                                }
                            });
                            if (params.some(param => param.seriesType === 'bar')) {
                                result += `<br/>总计: ${total}`;
                            }
                            return result;
                        };
                    }
                }

                // 标记线配置
                if (showMarkLine && s.showExtremum) {
                    const markLineColor = colors[index % colors.length];
                    baseSeriesConfig.markLine = {
                        silent: true,
                        symbolSize: 0,
                        animation: false,
                        label: {
                            show: true,
                            color: '#fff',
                            fontSize: 12,
                            formatter: (params) => {
                                if (!params.data) return '';
                                const value = typeof params.data.value === 'number'
                                    ? params.data.value.toFixed(2)
                                    : params.data.value;
                                return `${params.data.name}: ${value}`;
                            },
                            position: 'end',
                            backgroundColor: 'rgba(0,0,0,0.7)',
                            padding: [4, 8],
                            borderRadius: 4
                        },
                        lineStyle: {
                            color: markLineColor,
                            type: 'dashed',
                            width: 1,
                            opacity: 0.8
                        },
                        data: [
                            {
                                type: 'average',
                                name: '平均值',
                                valueIndex: 1
                            },
                            {
                                type: 'max',
                                name: '最大值',
                                valueIndex: 1
                            },
                            {
                                type: 'min',
                                name: '最小值',
                                valueIndex: 1
                            }
                        ]
                    };
                }

                return baseSeriesConfig;
            })
        };

        // 缩放配置
        if (iszoom) {
            baseConfig.dataZoom = [
                {
                    type: 'slider',
                    xAxisIndex: 0,
                    show: true,
                    height: 40,
                    bottom: 10,
                    start: 0,
                    end: defaultEnd,
                    textStyle: { color: '#fff', fontSize: 12 },
                    backgroundColor: 'rgba(255,255,255,0.1)',
                    fillerColor: 'rgba(255,255,255,0.2)',
                    borderColor: 'transparent',
                    handleSize: '100%',
                    handleStyle: {
                        color: '#fff',
                        borderColor: '#fff',
                        borderWidth: 1,
                        borderRadius: 10,
                        shadowBlur: 3,
                        shadowColor: 'rgba(0,0,0,0.4)'
                    },
                    selectedDataBackground: {
                        lineStyle: { color: '#fff' },
                        areaStyle: { color: 'rgba(255,255,255,0.2)' }
                    }
                },
                {
                    type: 'inside',
                    xAxisIndex: 0,
                    start: 0,
                    end: defaultEnd,
                    zoomOnMouseWheel: 'shift',
                    moveOnMouseWheel: true,
                    rangeMode: ['value', 'value']
                }
            ];
        }

        return {
            ...baseConfig,
            animation: true,
            animationDuration: 300,
            animationEasing: 'cubicOut',
            progressive: 500,
            progressiveThreshold: 3000,
            useDirtyRect: true,
            touchMoveThreshold: 5
        };
    });
};